package com.education.welco.controller;


import cn.hutool.core.date.DateUtil;
import com.education.common.pojo.AjaxResult;
import com.education.common.pojo.TStudent;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.welco.pojo.*;
import com.education.welco.pojo.vo.OrderPaperVo;
import com.education.welco.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.education.common.core.BaseController.writeJSON;


/**
 * 试卷表
 *
 * @date 2021-03-04 15:45:18
 */
@RestController
@RequestMapping("/orderpaper")
public class OrderPaperController {

    @Autowired
    private OrderPaperService orderPaperService;
    @Autowired
    private OrderPaperQuestionService orderPaperQuestionService;
    @Autowired
    private OrderQuestionService orderQuestionService;
    @Autowired
    private OrderAnswerService orderAnswerService;
    @Autowired
    private OrderUserPaperService orderUserPaperService;
    @Autowired
    private ITStudentService studentService;
    @Autowired
    private ISTheoryClassroomService theoryClassroomService;
    private static final Logger log = LoggerFactory.getLogger(OrderPaperController.class);


    //添加试卷
    @PostMapping("/addpaper")
    public void addparper(HttpServletResponse response, @RequestBody OrderPaper orderPaper) throws IOException {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(date);
        orderPaper.setCreateTime(format);
        int paper = orderPaperService.insertOrderPaper(orderPaper);
        writeJSON(paper, response, "200", "添加成功");
    }

    /**
     * 批量删除试卷
     *
     * @param response
     * @param orderPaper
     * @param ids
     * @throws IOException
     */
    @GetMapping("/deletepaper")
    public void deletequestion(HttpServletResponse response, OrderPaper orderPaper, String ids) throws IOException {
        //试卷id数组
        String[] split = ids.split(",");
        if (split.length == 0) {
            writeJSON(null, response, "201", "请选择要删除的试卷");
            return;
        }
        //判断试卷是否已被课堂关联
        OrderPaper orderPaperInfo = orderPaperService.selectOrderPaperById(Integer.valueOf(split[0]));
        //判断试卷是否到达答题时间
        Date startTime = orderPaperInfo.getStartTime();
        //根据课堂id查找是否有课堂
        STheoryClassroom sTheoryClassroom = new STheoryClassroom();
        sTheoryClassroom.setCatalogId(orderPaperInfo.getTopCatalogId());
        List<STheoryClassroom> theoryClassroomList = theoryClassroomService.selectSTheoryClassroomList(sTheoryClassroom);
        if (theoryClassroomList.size() > 0 && startTime.compareTo(new Date()) <= 0) {
            writeJSON(null, response, "201", "试卷已被开放作答，无法删除!");
            return;
        }
        //删除试卷以及中间表
        for (String s : split) {
            orderPaperService.deleteOrderPaperById(Integer.parseInt(s));
            //删除class_paper的关联记录
            orderPaperService.deleteClassPaperByPaperId(Integer.parseInt(s));
        }
        orderPaperQuestionService.deleteOrderPaperQuestionByIds(split);
        writeJSON(null, response, "200", "删除成功");
    }

    /**
     * 修改试卷接口
     * 试卷是否被班级排课-试卷是否到达答题时间
     *
     * @param response
     * @param orderPaper
     * @throws IOException
     */
    @PostMapping("/updatepaper")
    public void updatequestion(HttpServletResponse response, @RequestBody OrderPaperVo orderPaper) throws IOException {
        Integer id = orderPaper.getId();
        String[] ids = new String[1];
        ids[0] = id.toString();

        //判断试卷是否已被课堂关联
        OrderPaper orderPaperInfo = orderPaperService.selectOrderPaperById(id);
        //判断试卷是否到达答题时间
        Date startTime = orderPaperInfo.getStartTime();
        //根据课堂id查找是否有课堂
        STheoryClassroom sTheoryClassroom = new STheoryClassroom();
        sTheoryClassroom.setCatalogId(orderPaperInfo.getTopCatalogId());
        List<STheoryClassroom> theoryClassroomList = theoryClassroomService.selectSTheoryClassroomList(sTheoryClassroom);
        if (theoryClassroomList.size() > 0 && startTime.compareTo(new Date()) <= 0) {
            writeJSON(null, response, "201", "试卷已被开放作答，无法编辑!");
            return;
        }

        if (id != null) {
            orderPaperService.deleteOrderPaperById(id);
            orderPaperQuestionService.deleteOrderPaperQuestionByIds(ids);
            //删除class_paper的关联记录
            orderPaperService.deleteClassPaperByPaperId(id);
            orderPaper.setId(null);
            //orderPaper.setDelFlag();
            insert(response, orderPaper);
            writeJSON(null, response, "200", "修改成功");
        } else {
            writeJSON(null, response, "201", "输入错误");
        }
    }

    /**
     * 试卷试题详情
     *
     * @param paperId
     * @return
     */
    @GetMapping("/findByPaperId")
    public ApiReturnObject findById(Integer paperId) {
        int j = 1;
        OrderPaper paper = orderPaperService.selectOrderPaperById(paperId);
        if (paper != null) {
            //1 单选 2 判断 3 多选 4 简答
            List<OrderQuestion> squestionsList = orderQuestionService.selectOrderQuestionByPaperId(paperId, 1);
            for (OrderQuestion aSquestionsList : squestionsList) {
                aSquestionsList.setNum(j);
                j++;
            }
            paper.setSinglList(squestionsList);

            List<OrderQuestion> jquestionsList = orderQuestionService.selectOrderQuestionByPaperId(paperId, 2);
            for (OrderQuestion aJquestionsList : jquestionsList) {
                aJquestionsList.setNum(j);
                j++;
            }
            paper.setJudgeList(jquestionsList);

            List<OrderQuestion> mquestionsList = orderQuestionService.selectOrderQuestionByPaperId(paperId, 3);
            for (int i = 0; i < mquestionsList.size(); i++) {
                mquestionsList.get(i).setNum(j);
                j++;
            }
            paper.setManList(mquestionsList);

            List<OrderQuestion> aquestionsList = orderQuestionService.selectOrderQuestionByPaperId(paperId, 4);
            for (int i = 0; i < aquestionsList.size(); i++) {
                aquestionsList.get(i).setNum(j);
                j++;
            }
            paper.setAnsList(aquestionsList);


            return new ApiReturnObject("200", "操作成功", paper);
        } else {
            return new ApiReturnObject("201", "试卷ID错误！", paper);
        }
    }

    /**
     * 查询试卷列表
     *
     * @param response
     * @param orderPaper
     * @param pageSize
     * @param pageNum
     * @throws IOException
     */
    @GetMapping("/selectlist")
    public void selectquestionlist(HttpServletResponse response, OrderPaper orderPaper, Integer pageSize, Integer pageNum) throws IOException {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
        writeJSON(new PageInfo<>(orderPapers), response, "200", "查询成功");
    }

    /**
     * 教务端老师课堂考试组卷
     *
     * @param response
     * @param orderPaper
     * @throws IOException
     */
    @PostMapping("/paper/ins")
    public void insert(HttpServletResponse response, @RequestBody OrderPaperVo orderPaper) throws IOException {
        int length, sing, many, judg, answ;
        if (StringUtils.isNotEmpty(orderPaper.getSjTypearray())) orderPaper.setType(orderPaper.getSjTypearray()[0]);
        if (StringUtils.isNotEmpty(orderPaper.getSjLevelarray())) orderPaper.setLevel(orderPaper.getSjLevelarray()[0]);
        if (StringUtils.isNotEmpty(orderPaper.getDelFlagarray()))
            orderPaper.setDelFlag(orderPaper.getDelFlagarray()[0]);
        String catalogId = orderPaper.getCatalogId();
        //2 随机出题 1 手动出题 delFlag
        if ("2".equals(orderPaper.getDelFlag())) {
            /*1 单选 2 判断 3 多选 4 简答
            查询试题逻辑--查全部
            查出所有单选题*/
            String[] sinIds = orderQuestionService.selectIdsByTypelf(1, catalogId);
            //查出所有判断题
            String[] judgIds = orderQuestionService.selectIdsByTypelf(2, catalogId);
            //查出所有多选题
            String[] manyIds = orderQuestionService.selectIdsByTypelf(3, catalogId);
            //查出所有简答题
            String[] answIds = orderQuestionService.selectIdsByTypelf(4, catalogId);


            if (Integer.parseInt(orderPaper.getSingle()) > sinIds.length) {
                writeJSON(null, response, "201", "单选个数超出范围");
                return;
            }
            if (Integer.parseInt(orderPaper.getMany()) > manyIds.length) {
                writeJSON(null, response, "201", "多选个数超出范围");
                return;
            }
            if (Integer.parseInt(orderPaper.getJudgment()) > judgIds.length) {
                writeJSON(null, response, "201", "判断个数超出范围");
                return;
            }
            if (Integer.parseInt(orderPaper.getAnsw()) > answIds.length) {
                writeJSON(null, response, "201", "简答个数超出范围");
                return;
            }
            //对应题型题目的集合
            List<Integer> danxuan = new ArrayList<>();
            List<Integer> duoxuan = new ArrayList<>();
            List<Integer> panduan = new ArrayList<>();
            List<Integer> jianda = new ArrayList<>();
            //试题总个数 length
            length = (sing = Integer.parseInt(orderPaper.getSingle())) + (many = Integer.parseInt(orderPaper.getMany())) + (judg = Integer.parseInt(orderPaper.getJudgment())) + (answ = Integer.parseInt(orderPaper.getAnsw()));
            //题目集合
            List<String> list = new ArrayList<>();
            for (int i = 0; i < sing; i++) {
                int i1 = random(Integer.parseInt(orderPaper.getSingle()), danxuan);
                list.add(sinIds[i1]);
            }
            for (int i = 0; i < many; i++) {
                int i2 = random(Integer.parseInt(orderPaper.getMany()), duoxuan);
                list.add(manyIds[i2]);
            }
            for (int i = 0; i < judg; i++) {
                int i3 = random(Integer.parseInt(orderPaper.getJudgment()), panduan);
                list.add(judgIds[i3]);
            }
            for (int i = 0; i < answ; i++) {
                int i4 = random(Integer.parseInt(orderPaper.getAnsw()), jianda);
                list.add(answIds[i4]);
            }
            String[] strings = list.toArray(new String[list.size()]);
            orderPaper.setQuestionIds(strings);
            //添加试卷
            Date date1 = new Date();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = dateFormat1.format(date1);
            orderPaper.setCreateTime(format1);//试卷创建日期
            //补充试卷的课程顶级id
            int i = orderPaperService.insertPaperTest(orderPaper);
            //新增试卷后在class_paper添加试卷班级关联记录
            insertPaperToClassPaper(orderPaper.getId(), orderPaper.getTopCatalogId(), orderPaper.getCreateuser());
            //添加试卷试题关联
            String[] questionIds = orderPaper.getQuestionIds();//试题集合数组
            for (int i1 = 0; i1 < questionIds.length; i1++) {
                OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();//关联表对象
                orderPaperQuestion.setPaperId(orderPaper.getId());
                orderPaperQuestion.setQuestionId(Integer.parseInt(questionIds[i1]));
                orderPaperQuestionService.insertOrderPaperQuestion(orderPaperQuestion);
            }
            writeJSON(null, response, "200", "添加成功");
        }
        //2 随机出题 1 手动出题 delFlag
        if ("1".equals(orderPaper.getDelFlag())) {
            //把数组整合到一起
            String[] signarr = StringUtils.isNotEmpty(orderPaper.getSingleList()) ? orderPaper.getSingleList().split(",") : new String[0];//单选
            String[] manyarr = StringUtils.isNotEmpty(orderPaper.getManyList()) ? orderPaper.getManyList().split(",") : new String[0];//多选
            String[] judgarr = StringUtils.isNotEmpty(orderPaper.getJudgmentList()) ? orderPaper.getJudgmentList().split(",") : new String[0];//判断
            String[] answarr = StringUtils.isNotEmpty(orderPaper.getAnswList()) ? orderPaper.getAnswList().split(",") : new String[0];//简答
            length = (sing = signarr.length) + (many = manyarr.length) + (judg = judgarr.length) + (answ = answarr.length);
            String[] array = new String[length];//开辟空数组空间，保存id
            System.arraycopy(signarr, 0, array, 0, sing);
            System.arraycopy(manyarr, 0, array, sing, many);
            System.arraycopy(judgarr, 0, array, many + sing, judg);
            System.arraycopy(answarr, 0, array, many + sing + judg, answ);
            orderPaper.setQuestionIds(array);

            Date date1 = new Date();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = dateFormat1.format(date1);
            orderPaper.setCreateTime(format1);
            int i = orderPaperService.insertPaperTest(orderPaper);
            //新增试卷后在class_paper添加试卷班级关联记录
            insertPaperToClassPaper(orderPaper.getId(), orderPaper.getTopCatalogId(), orderPaper.getCreateuser());
            //添加试卷试题关联
            String[] questionIds = orderPaper.getQuestionIds();
            for (int i1 = 0; i1 < questionIds.length; i1++) {
                OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
                orderPaperQuestion.setPaperId(orderPaper.getId());
                orderPaperQuestion.setQuestionId(Integer.parseInt(questionIds[i1]));
                orderPaperQuestionService.insertOrderPaperQuestion(orderPaperQuestion);
            }
            writeJSON(null, response, "200", "添加成功");
        }
    }

    /**
     * 新增试卷后在class_paper添加试卷班级关联记录
     *
     * @param paperId      试卷id
     * @param topCatalogId 课程id
     */
    public void insertPaperToClassPaper(Integer paperId, Integer topCatalogId, String teaUserId) {
        //s_theory_classroom表获取classId(课程id)
        List<Integer> classIdList = theoryClassroomService.selectClassIdsByCatalogId(topCatalogId);
        if (classIdList.size() == 0) {
            return;
        }
        orderPaperService.insertClassPaper(classIdList, paperId, teaUserId);
    }

    /**
     * 随机获取试题id
     *
     * @param size
     * @param ran
     * @return
     */
    private int random(int size, List<Integer> ran) {
        Integer i = 0;
        Random random = new Random();
        if (!ran.contains(i = random.nextInt(size))) {
            ran.add(i);
            return i;
        }
        return random(size, ran);
    }

    //查询试卷列表
    @GetMapping("/selectpaperlist")
    public void selectpaperlist(HttpServletResponse response, Integer pageSize, Integer pageNum, String userId) throws IOException {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        OrderPaper orderPaper = new OrderPaper();
        orderPaper.setCreateuser(userId);
        List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
        writeJSON(new PageInfo<>(orderPapers), response, "200", "查询成功");
    }

    //查询试卷详情
    @GetMapping("/selectpaperdetails")
    public void selectpaperdetails(HttpServletResponse response, OrderPaperQuestion orderPaperQuestion) throws IOException {
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        ArrayList<Object> list = new ArrayList<>();
        for (OrderPaperQuestion paperQuestion : orderPaperQuestions) {
            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(paperQuestion.getQuestionId());
            list.add(orderQuestion);
        }
        writeJSON(list, response, "200", "查询成功");

    }

    //发布试卷
    @PostMapping("/releasetestpaper")
    public void releasetestpaper(HttpServletResponse response, HttpServletRequest request) throws IOException {
        Integer paperId = Integer.valueOf(request.getParameter("paperId"));
        Integer classId = Integer.valueOf(request.getParameter("classId"));
        OrderPaper paper = orderPaperService.selectOrderPaperById(paperId);
        paper.setClassId(classId);
        orderPaperService.updateOrderPaper(paper);
        writeJSON(null, response, "200", "发布成功");
    }

    //查询批阅列表
    @GetMapping("/selectReviewlist")
    public void selectReviewlist(HttpServletResponse response, OrderPaper orderPaper, Integer pageSize, Integer pageNum) throws IOException {
        //根据班级id查询发布出去的试卷
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
        ArrayList<Object> arrayList = new ArrayList<>();
        for (OrderPaper paper : orderPapers) {
            Integer id = paper.getId();

            //提交人数
            String[] strings = orderAnswerService.selectOrderSubmit(id);
            int length = strings.length;

            //总人数
            Integer classId = paper.getClassId();
            List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
            int size = selectstudentlist.size();
            paper.setClassSize(size);
            paper.setSubmitnum(length);
            //arrayList.add(paper);
        }
        writeJSON(new PageInfo<>(orderPapers), response, "200", "查询成功");
    }

    /**
     * 系统评分
     *
     * @param orderAnswer-userId,paperId
     * @throws IOException
     * @time
     */
    @GetMapping("/systemScore")
    public void systemScore(HttpServletResponse response, OrderAnswer orderAnswer) throws IOException {
        //先得到学生的答案
        List<OrderAnswer> orderAnswers = orderAnswerService.selectOrderAnswerList(orderAnswer);
        Integer paperId = orderAnswer.getPaperId();
        OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);

        //得到该套试卷各种题型相应的分数
        String singleScore = orderPaper.getSingleScore();
        String judgmentScore = orderPaper.getJudgmentScore();
        String manyScore = orderPaper.getManyScore();

        for (OrderAnswer answer : orderAnswers) {
            //学生答案
            String answer1 = answer.getAnswer();
            //正确答案
            String stanswer = answer.getStanswer();

            Integer questionId = answer.getQuestionId();
            Integer paperId1 = answer.getPaperId();
            Integer userId = answer.getUserId();

            Integer type = answer.getType();
            //单选
            if (type.equals(1)) {
                if (answer1.equals(stanswer)) {
                    //若相等，则填入该题相应的分数
                    OrderAnswer orderAnswer1 = new OrderAnswer();
                    orderAnswer1.setQuestionId(questionId);
                    orderAnswer1.setPaperId(paperId1);
                    orderAnswer1.setUserId(userId);
                    orderAnswer1.setScore(Integer.parseInt(singleScore));
                    orderAnswerService.updateOrderAnswer1(orderAnswer1);
                } else {
                    OrderAnswer orderAnswer1 = new OrderAnswer();
                    orderAnswer1.setQuestionId(questionId);
                    orderAnswer1.setPaperId(paperId1);
                    orderAnswer1.setUserId(userId);
                    orderAnswer1.setScore(0);
                    orderAnswerService.updateOrderAnswer1(orderAnswer1);
                }
            }
            //判断
            if (type.equals(2)) {
                if (answer1.equals(stanswer)) {
                    //若相等，则填入该题相应的分数
                    OrderAnswer orderAnswer1 = new OrderAnswer();
                    orderAnswer1.setQuestionId(questionId);
                    orderAnswer1.setPaperId(paperId1);
                    orderAnswer1.setUserId(userId);
                    orderAnswer1.setScore(Integer.parseInt(judgmentScore));
                    orderAnswerService.updateOrderAnswer1(orderAnswer1);
                } else {
                    OrderAnswer orderAnswer1 = new OrderAnswer();
                    orderAnswer1.setQuestionId(questionId);
                    orderAnswer1.setPaperId(paperId1);
                    orderAnswer1.setUserId(userId);
                    orderAnswer1.setScore(0);
                    orderAnswerService.updateOrderAnswer1(orderAnswer1);
                }
            }
            //多选
            if (type.equals(3)) {
                String[] split = answer1.split(",");
                String[] split1 = stanswer.split(",");
                Arrays.sort(split);
                Arrays.sort(split1);
                if (Arrays.equals(split, split1)) {
                    //若相等，则填入该题相应的分数
                    OrderAnswer orderAnswer1 = new OrderAnswer();
                    orderAnswer1.setQuestionId(questionId);
                    orderAnswer1.setPaperId(paperId1);
                    orderAnswer1.setUserId(userId);
                    orderAnswer1.setScore(Integer.parseInt(manyScore));
                    orderAnswerService.updateOrderAnswer1(orderAnswer1);
                } else {
                    OrderAnswer orderAnswer1 = new OrderAnswer();
                    orderAnswer1.setQuestionId(questionId);
                    orderAnswer1.setPaperId(paperId1);
                    orderAnswer1.setUserId(userId);
                    orderAnswer1.setScore(0);
                    orderAnswerService.updateOrderAnswer1(orderAnswer1);
                }
            }
        }
        writeJSON(null, response, "200", "success");
    }

    //查询批阅列表
    @GetMapping("/selectReview")
    public void selectReview(HttpServletResponse response, Integer classId, Integer paperId, Integer pageSize, Integer pageNum) throws IOException {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
        ArrayList<Object> arrayList = new ArrayList<>();
        for (TStudent tStudent : selectstudentlist) {
            Integer userId = tStudent.getUserId();
            OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
            //1 男 2 女
            //orderUserPaper.setStudentSex(tStudent.getStudentSex());
            OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
            if (orderUserPaper != null) {
                String level = orderPaper.getLevel();
                orderUserPaper.setLevel(level);
                arrayList.add(orderUserPaper);
            }
        }
        writeJSON(new PageInfo<>(arrayList), response, "200", "查询成功");
    }

    //未批阅查看
    @GetMapping("/unreviewedView")
    public void unreviewedView(HttpServletResponse response, OrderAnswer orderAnswer) throws IOException {
        Integer paperId = orderAnswer.getPaperId();
        Integer userId = orderAnswer.getUserId();
        OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
        orderPaperQuestion.setPaperId(paperId);

        ArrayList<OrderQuestion> arrayList = new ArrayList<>();

        //查询试题列表
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        for (OrderPaperQuestion paperQuestion : orderPaperQuestions) {
            Integer questionId = paperQuestion.getQuestionId();

            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);

            OrderAnswer orderAnswer1 = orderAnswerService.selectOrderAnswerList3(orderAnswer.getPaperId(), userId, questionId);
            String answer2 = orderAnswer1.getAnswer();

            Integer score = orderAnswer1.getScore();
            orderQuestion.setXsAnswer(answer2);
            orderQuestion.setScorequestion(score);

            arrayList.add(orderQuestion);
        }
        for (OrderQuestion orderQuestion : arrayList) {
            String questionType = orderQuestion.getQuestionType();
            //1 单选 2 判断 3 多选 4 简答
            OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
            if ("1".equals(questionType)) {
                orderQuestion.setSingleScore(Integer.parseInt(orderPaper.getSingleScore()));
            }
            if ("2".equals(questionType)) {
                orderQuestion.setJudgmentScore(Integer.parseInt(orderPaper.getJudgmentScore()));
            }
            if ("3".equals(questionType)) {
                orderQuestion.setManyScore(Integer.parseInt(orderPaper.getManyScore()));
            }
            if ("4".equals(questionType)) {
                orderQuestion.setShortAnswerScore(Integer.parseInt(orderPaper.getAnswSore()));
            }
        }
        writeJSON(arrayList, response, "200", "查询成功");
    }

    //添加批阅分数
    @PostMapping("/addReviewScore")
    public void addReviewScore(HttpServletResponse response, @RequestBody List<OrderAnswer> orderAnswer) throws IOException {
        //参数 questionId paperId score
        BigDecimal b0 = new BigDecimal(0);
        BigDecimal b1 = new BigDecimal(0);
        OrderUserPaper orderUserPaper = new OrderUserPaper();

        for (OrderAnswer answer : orderAnswer) {
            Integer paperId = answer.getPaperId();
            Integer questionId = answer.getQuestionId();
            Integer userId = answer.getUserId();
            OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
            String level = orderPaper.getLevel();
            //1人工 2系统
            if (level.equals("1")) {
                //填入学生每道题分数
                orderAnswerService.updateOrderAnswer1(answer);//加入userId条件
                Integer score = answer.getScore();
                BigDecimal big2 = new BigDecimal(score.toString());
                //分数
                b0 = b0.add(big2);
                String comment = answer.getComment();
                orderUserPaper.setComment(comment);

                orderUserPaper.setScore(b0.toString());
                orderUserPaper.setPaperId(paperId);
                orderUserPaper.setUserId(userId.toString());
                orderUserPaper.setType(1);
                //填入总分
                orderUserPaperService.update(orderUserPaper);

            } else {
                Integer type = answer.getType();
                if (!type.equals(4)) {
                    OrderAnswer orderAnswer1 = orderAnswerService.selectOrderAnswerList3(paperId, userId, questionId);
                    Integer score = orderAnswer1.getScore();
                    BigDecimal bigDecimal = new BigDecimal(score.toString());
                    b0 = b0.add(bigDecimal);
                    String comment = answer.getComment();
                    orderUserPaper.setComment(comment);

                } else {
                    orderAnswerService.updateOrderAnswer1(answer);//加入userId条件
                    Integer score = answer.getScore();
                    BigDecimal bigDecimal = new BigDecimal(score);
                    b0 = b0.add(bigDecimal);
                    String comment = answer.getComment();
                    orderUserPaper.setComment(comment);
                }

                orderUserPaper.setScore(b0.toString());
                orderUserPaper.setPaperId(paperId);
                orderUserPaper.setUserId(userId.toString());
                orderUserPaper.setType(1);
                //填入总分
                orderUserPaperService.update(orderUserPaper);

            }
        }

        writeJSON(null, response, "200", "评分成功");
    }

    //成绩查询
    @GetMapping("/resultInquiry")
    public void resultInquiry(HttpServletResponse response, OrderAnswer orderAnswer) throws IOException {
        Integer paperId = orderAnswer.getPaperId();
        OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
        orderPaperQuestion.setPaperId(paperId);

        Integer userId = orderAnswer.getUserId();

        ArrayList<Object> arrayList = new ArrayList<>();

        //查询试题列表
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        for (OrderPaperQuestion paperQuestion : orderPaperQuestions) {
            Integer questionId = paperQuestion.getQuestionId();

            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);

            //OrderAnswer orderAnswer1 = orderAnswerService.selectOrderAnswerList2(orderAnswer.getPaperId(), questionId);
            OrderAnswer orderAnswer1 = orderAnswerService.selectOrderAnswerList3(paperId, userId, questionId);
            OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
            String comment = orderUserPaper.getComment();
            String answer2 = orderAnswer1.getAnswer();
            Integer score = orderAnswer1.getScore();
            orderQuestion.setScorequestion(score);
            orderQuestion.setXsAnswer(answer2);
            orderQuestion.setComment(comment);
            arrayList.add(orderQuestion);

        }
        writeJSON(arrayList, response, "200", "查询成功");
    }


    //查询批阅列表
    @GetMapping("/selectReviewlist1")
    public void selectReviewlist1(HttpServletResponse response, OrderPaper orderPaper, Integer pageSize, Integer pageNum, String ktime, String jtime) throws IOException {
        Date parse1 = DateUtil.parse(ktime);
        Date parse2 = DateUtil.parse(jtime);
        //根据班级id查询发布出去的试卷
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        String introduction = orderPaper.getIntroduction();

        //三个都不为空
        if (!introduction.equals("") && parse1 != null && parse2 != null) {
            ArrayList<Object> arrayList = new ArrayList<>();
            List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
            for (OrderPaper paper : orderPapers) {
                Integer id = paper.getId();


                String createTime = paper.getCreateTime();
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = format1.parse(createTime);
                    if (parse.before(parse2) && parse.after(parse1)) {
                        //提交人数
                        String[] strings = orderAnswerService.selectOrderSubmit(id);
                        int length = strings.length;

                        //批阅人数
                        List<OrderUserPaper> orderUserPapers = orderUserPaperService.OrderUserPaperlist3(id);
                        int size1 = orderUserPapers.size();

                        //总人数
                        Integer classId = paper.getClassId();
                        List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
                        int size = selectstudentlist.size();
                        paper.setClassSize(size);
                        paper.setSubmitnum(length);
                        paper.setReview(size1);
                        arrayList.add(paper);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            writeJSON(new PageInfo<>(arrayList), response, "200", "查询成功");
        }
        //三个都为空
        if (introduction.equals("") && parse1 == null && parse2 == null) {
            List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
            //ArrayList<Object> arrayList = new ArrayList<>();
            for (OrderPaper paper : orderPapers) {
                Integer id = paper.getId();
                //提交人数
                String[] strings = orderAnswerService.selectOrderSubmit(id);
                int length = strings.length;

                //批阅人数
                List<OrderUserPaper> orderUserPapers = orderUserPaperService.OrderUserPaperlist3(id);
                int size1 = orderUserPapers.size();

                //总人数
                Integer classId = paper.getClassId();
                List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
                int size = selectstudentlist.size();
                paper.setClassSize(size);
                paper.setSubmitnum(length);
                paper.setReview(size1);
                //arrayList.add(paper);
            }
            writeJSON(new PageInfo<>(orderPapers), response, "200", "查询成功");

        }
        //只有试卷名称  模糊查询
        if (!introduction.equals("")) {
            List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
            for (OrderPaper paper : orderPapers) {
                Integer id = paper.getId();
                //提交人数
                String[] strings = orderAnswerService.selectOrderSubmit(id);
                int length = strings.length;

                //批阅人数
                List<OrderUserPaper> orderUserPapers = orderUserPaperService.OrderUserPaperlist3(id);
                int size1 = orderUserPapers.size();

                //总人数
                Integer classId = paper.getClassId();
                List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
                int size = selectstudentlist.size();
                paper.setClassSize(size);
                paper.setSubmitnum(length);
                paper.setReview(size1);
                //arrayList.add(paper);
            }
            writeJSON(new PageInfo<>(orderPapers), response, "200", "查询成功");
        }
        //只有时间
        if (ktime != null && jtime != null) {
            ArrayList<OrderPaper> arrayList = new ArrayList<>();
            List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
            for (OrderPaper paper : orderPapers) {
                Integer id = paper.getId();

                String createTime = paper.getCreateTime();
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = format1.parse(createTime);
                    if (parse.before(parse2) && parse.after(parse1)) {
                        //提交人数
                        String[] strings = orderAnswerService.selectOrderSubmit(id);
                        int length = strings.length;

                        //批阅人数
                        List<OrderUserPaper> orderUserPapers = orderUserPaperService.OrderUserPaperlist3(id);
                        int size1 = orderUserPapers.size();

                        //总人数
                        Integer classId = paper.getClassId();
                        List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
                        int size = selectstudentlist.size();
                        paper.setClassSize(size);
                        paper.setSubmitnum(length);
                        paper.setReview(size1);
                        arrayList.add(paper);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            writeJSON(new PageInfo<>(arrayList), response, "200", "查询成功");
        }

    }

    //根据班级id查出该班下成绩列表
    @GetMapping("/classscore")
    public void classscore(HttpServletResponse response, Integer classId, Integer paperId, Integer pageSize, Integer pageNum) throws IOException {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<TStudent> selectstudentlist = studentService.selectTStudentList1(classId);
        ArrayList<Object> list = new ArrayList<>();
        for (TStudent tStudent : selectstudentlist) {
            Integer userId = tStudent.getUserId();
            OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper1(paperId, userId);
            if (orderUserPaper != null) {
                OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
                String introduction = orderPaper.getIntroduction();
                String createTime = orderPaper.getCreateTime();
                orderUserPaper.setPaperName(introduction);
                orderUserPaper.setCreateTime(createTime);
                list.add(orderUserPaper);
            } else {
                continue;
            }

        }
        writeJSON(new PageInfo<>(list), response, "200", "成功");
    }

    //成绩查询
    @GetMapping("/resultInquiry1")
    public void resultInquiry1(HttpServletResponse response, OrderAnswer orderAnswer) throws IOException {
        Integer paperId = orderAnswer.getPaperId();
        Integer userId1 = orderAnswer.getUserId();
        OrderUserPaper orderUserPaper1 = orderUserPaperService.SelectOrderUserPaper1(paperId, userId1);


        String comment = orderUserPaper1.getComment();
        OrderPaper orderPaper1 = orderPaperService.selectOrderPaperById(paperId);
        String level = orderPaper1.getLevel();
        OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
        orderPaperQuestion.setPaperId(paperId);

        ArrayList<Object> list = new ArrayList<>();


        HashMap<Object, Object> map = new HashMap<>();
        //查询试题列表
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        for (OrderPaperQuestion paperQuestion : orderPaperQuestions) {
            Integer questionId = paperQuestion.getQuestionId();

            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);

            OrderAnswer orderAnswer1 = orderAnswerService.selectOrderAnswerList3(paperId, orderAnswer.getUserId(), questionId);
            Integer score = orderAnswer1.getScore();
            String answer2 = orderAnswer1.getAnswer();
            orderQuestion.setScorequestion(score);
            orderQuestion.setXsAnswer(answer2);
            String createTime = orderQuestion.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                String stamp = String.valueOf(sdf.parse(createTime).getTime());
                orderQuestion.setCreateTime(stamp);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            list.add(orderQuestion);
        }

        OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);

        BigDecimal Single = new BigDecimal(orderPaper.getSingle());
        BigDecimal SingleScore = new BigDecimal(orderPaper.getSingleScore());
        BigDecimal Judgment = new BigDecimal(orderPaper.getJudgment());
        BigDecimal JudgmentScore = new BigDecimal(orderPaper.getJudgmentScore());
        BigDecimal many = new BigDecimal(orderPaper.getManyScore());
        BigDecimal manyScore = new BigDecimal(orderPaper.getSingle());
        BigDecimal answ = new BigDecimal(orderPaper.getAnsw());
        BigDecimal answSore = new BigDecimal(orderPaper.getAnswSore());

        BigDecimal add = Single.multiply(SingleScore).add(Judgment.multiply(JudgmentScore)).add(many.multiply(manyScore)).add(answ.multiply(answSore));

        Integer userId = orderAnswer.getUserId();
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        String score = orderUserPaper.getScore();


        map.put("list", list);
        map.put("zongfen", add);
        map.put("fenshu", score);
        map.put("level", level);
        map.put("comment", comment);

        writeJSON(map, response, "200", "查询成功");
    }

    /**
     * 克隆试卷
     *
     * @param orderPaper
     * @return
     */
    @PostMapping("/clone")
    public AjaxResult clone(@RequestBody OrderPaper orderPaper) {
        Integer id = orderPaper.getId();
        if (id == null) {
            return new AjaxResult(201, "缺少参数");
        }
        try {
            orderPaperService.clone(orderPaper);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("clone error", e);
            return AjaxResult.error();
        }
    }
}
